package top.fangwenmagician.calculationstring.operator;

import top.fangwenmagician.calculationstring.ProcessControl;
import top.fangwenmagician.calculationstring.exception.CalculationException;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * <h1>普通正则运算符抽象类</h1>
 * 该类提供了一种简单的{@link I_Operator}实现<br />
 * 可以通过继承该抽象类，实现一个基于 普通正则捕获组 的运算符
 */
public abstract class A_NormalRegularOperator extends A_RegularOperator {
    /**
     * 不使用命名捕获组时触发的的计算函数
     *
     * @param captureStrings 被捕获的对象数组
     * @param processControl 流程控制器，可用于回调计算或获取自定义配置
     * @return 运算的结果
     * @throws Exception 计算中抛出的异常
     */
    public abstract String calculation(String[] captureStrings, ProcessControl processControl) throws Exception;

    @Override
    public String calculation(String expression, ProcessControl processControl) throws Exception {
        Pattern pattern = Pattern.compile(this.regularText());
        Matcher matcher = pattern.matcher(expression);
        if (matcher.find()) {
            String[] strings = new String[matcher.groupCount() + 1];
            for (int i = 0; i < strings.length; i++) {
                strings[i] = matcher.group(i);
            }
            String calculationResults = matcher.replaceFirst(this.calculation(strings, processControl));
            processControl.writeLog(calculationResults);
            return calculationResults;
        } else {
            throw new CalculationException("未捕获到字符串");
        }
    }
}
